package com.zz.admin.auth.extension;

import cn.hutool.core.util.ObjectUtil;
import com.zz.admin.auth.dto.DefaultUserDetails;
import com.zz.admin.auth.enums.BaseAuthExceptionEnum;
import com.zz.admin.userManagement.dto.UserDto;
import com.zz.admin.userManagement.dto.UserRoleMenuDto;
import com.zz.admin.userManagement.service.UserService;
import com.zz.common.constants.BaseConstant;
import com.zz.common.exception.ExceptionFactory;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.*;

@Slf4j
@Service
public class MyUserDetailsService implements UserDetailsService {

    @Resource
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        UserDto userDto = userService.queryByLoginAccount(username);
        if (ObjectUtil.isNull(userDto)) {
            // 用户名不存在
            throw ExceptionFactory.createBaseException(BaseAuthExceptionEnum.USERNAME_NOT_FOUND);
        } else if (BaseConstant.NO.equals(userDto.getStatus()) || BaseConstant.YES.equals(userDto.getDelFlag())) {
            // 该用户账号已失效
            throw ExceptionFactory.createBaseException(BaseAuthExceptionEnum.INVALIDITY_USER);
        }

        // 获取用户权限
        List<String> permissions = getAuthorities(userDto.getUserId());
        return new DefaultUserDetails(userDto, permissions);
    }

    private List<String> getAuthorities(String userId) {
        List<UserRoleMenuDto> userRoleMenuDtos = userService.queryRoleAndMenuByUserId(userId);
        Set<String> res = new HashSet<>();
        for (UserRoleMenuDto userRoleMenuDto : userRoleMenuDtos) {
            String roleCode = userRoleMenuDto.getRoleCode();
            if (StringUtils.isNotBlank(roleCode)) {
                res.add("ROLE_" + roleCode);
            }
            String permissions = userRoleMenuDto.getPermission();
            if (StringUtils.isNotBlank(permissions)) {
                res.addAll(Arrays.asList(permissions.split(";")));
            }
        }
        return new ArrayList<>(res);
    }
}
